<template>
  <div class="downloads-page">
    <div class="container-custom py-8">
      <h1 class="text-3xl font-bold mb-8">下载中心</h1>
      
      <div v-if="pending" class="space-y-4">
        <div v-for="i in 5" :key="i" class="card p-6 animate-pulse">
          <div class="h-20 bg-gray-200 rounded" />
        </div>
      </div>
      
      <div v-else-if="downloads.length === 0" class="text-center py-16">
        <div class="i-mdi-download-outline text-8xl text-gray-300 mb-4" />
        <p class="text-gray-600 mb-4">还没有已购买的项目</p>
        <NuxtLink to="/products" class="btn-primary">
          去购买
        </NuxtLink>
      </div>
      
      <div v-else>
        <div class="space-y-4">
          <div
            v-for="item in downloads"
            :key="item.id"
            class="card p-6"
          >
            <div class="flex items-center space-x-6">
              <!-- 产品图片 -->
              <NuxtLink :to="`/products/${item.product.id}`" class="flex-shrink-0">
                <NuxtImg
                  :src="item.product.cover"
                  :alt="item.product.title"
                  class="w-32 h-32 object-cover rounded"
                />
              </NuxtLink>
              
              <!-- 产品信息 -->
              <div class="flex-1 min-w-0">
                <NuxtLink
                  :to="`/products/${item.product.id}`"
                  class="text-xl font-bold hover:text-primary-600 line-clamp-1"
                >
                  {{ item.product.title }}
                </NuxtLink>
                
                <p class="text-sm text-gray-600 mt-2 line-clamp-2">
                  {{ item.product.description }}
                </p>
                
                <div class="flex flex-wrap gap-2 mt-3">
                  <Tag v-for="tech in item.product.tech.slice(0, 5)" :key="tech" size="sm">
                    {{ tech }}
                  </Tag>
                </div>
                
                <div class="mt-3 text-sm text-gray-500">
                  购买时间：{{ formatDate(item.purchasedAt) }}
                </div>
              </div>
              
              <!-- 下载按钮 -->
              <div class="flex flex-col space-y-2">
                <button
                  class="btn-primary px-6 py-3 whitespace-nowrap"
                  @click="handleDownload(item.product.id)"
                >
                  <div class="i-mdi-download inline-block mr-2" />
                  下载源码
                </button>
                <NuxtLink
                  :to="`/products/${item.product.id}`"
                  class="btn-outline px-6 py-3 text-center whitespace-nowrap"
                >
                  查看详情
                </NuxtLink>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="totalPages > 1" class="mt-8 flex justify-center">
          <div class="flex items-center space-x-2">
            <button
              class="btn-outline px-3 py-2"
              :disabled="currentPage === 1"
              @click="currentPage--"
            >
              上一页
            </button>
            <span class="text-sm text-gray-600">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              class="btn-outline px-3 py-2"
              :disabled="currentPage === totalPages"
              @click="currentPage++"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'

definePageMeta({
  middleware: 'auth',
})

const currentPage = ref(1)

const { data: response, pending } = await useFetch('/api/user/downloads', {
  query: computed(() => ({
    page: currentPage.value,
    pageSize: 10,
  })),
  watch: [currentPage],
})

const downloads = computed(() => response.value?.data?.items || [])
const totalPages = computed(() => response.value?.data?.pagination?.totalPages || 1)

function formatDate(date: string) {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

async function handleDownload(productId: string) {
  try {
    // 获取下载链接
    const { data } = await $fetch(`/api/products/${productId}/download`) as any
    
    // 创建隐藏的 a 标签并点击下载
    const link = document.createElement('a')
    link.href = data.downloadUrl
    link.download = data.filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error: any) {
    alert(error.message || '下载失败')
  }
}

// SEO
useSeoMeta({
  title: '下载中心 - 代码小库',
  robots: 'noindex',
})
</script>

<style scoped>
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>

